import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.Timer;


public class Controller extends KeyAdapter implements ActionListener {
	private ViewI view;
	private Timer t;
	
	Controller(ViewI v){
		t = new Timer(1000, this);
		this.view=v;
	}
	public void actionPerformed(ActionEvent e){
		if(e.getSource().equals(t) && Master.getActualLevel().getPlayersOnTrack()){ 
			for (int i=0;i<Master.getActualLevel().getPlayersNumber(); i++){
				Log.cmd="MOVE DOWN p"+i;
				Master.getActualLevel().getPlayer(i).changeMyPosition(Direction.DOWN);
			}
		}
		view.redraw(Master.getActualLevel());
	}
	
	public void keyPressed(KeyEvent e){
		int c;
		c=e.getKeyCode();
		if(Master.getActualLevel().getPlayersOnTrack()){
			switch(c){
			case KeyEvent.VK_RIGHT:
				Log.cmd="MOVE RIGHT p0";
				Master.getActualLevel().getPlayer(0).changeMyPosition(Direction.RIGHT);
				break;
			case KeyEvent.VK_LEFT:
				Log.cmd="MOVE LEFT p0";
				Master.getActualLevel().getPlayer(0).changeMyPosition(Direction.LEFT);
				break;
			case KeyEvent.VK_UP:
				Log.cmd="MOVE UP p0";
				Master.getActualLevel().getPlayer(0).changeMyPosition(Direction.UP);
				break;
			case KeyEvent.VK_DOWN:
				Log.cmd="MOVE DOWN p0";
				Master.getActualLevel().getPlayer(0).changeMyPosition(Direction.DOWN);
				break;
			case KeyEvent.VK_D:
				Log.cmd="MOVE RIGHT p1";
				Master.getActualLevel().getPlayer(1).changeMyPosition(Direction.RIGHT);
				break;
			case KeyEvent.VK_A:
				Log.cmd="MOVE LEFT p1";
				Master.getActualLevel().getPlayer(1).changeMyPosition(Direction.LEFT);
				break;
			case KeyEvent.VK_W:
				Log.cmd="MOVE UP p1";
				Master.getActualLevel().getPlayer(1).changeMyPosition(Direction.UP);
				break;
			case KeyEvent.VK_S:
				Log.cmd="MOVE DOWN p1";
				Master.getActualLevel().getPlayer(1).changeMyPosition(Direction.DOWN);
				break;
			case KeyEvent.VK_SPACE:
				Master.getActualLevel().setPlayersOnTrack(!Master.getActualLevel().getPlayersOnTrack());
				t.stop();
			default: 
				break;
			}
		}
		else{
			switch(c){
			case KeyEvent.VK_RIGHT:
				Master.getActualLevel().moveTrack(Direction.RIGHT);
				break;
			case KeyEvent.VK_LEFT:
				Master.getActualLevel().moveTrack(Direction.LEFT);
				break;
			case KeyEvent.VK_UP:
				Master.getActualLevel().moveTrack(Direction.UP);
				break;
			case KeyEvent.VK_DOWN:
				Master.getActualLevel().moveTrack(Direction.DOWN);
				break;
			case KeyEvent.VK_SPACE:
				Master.getActualLevel().setPlayersOnTrack(!Master.getActualLevel().getPlayersOnTrack());
				t.start();
			default: 
				break;
			}
		}
		view.redraw(Master.getActualLevel());
		t.restart();
	}
}
